package me.chan.chatting.server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import me.chan.chatting.server.factory.GroupServiceFactory;
import me.chan.chatting.server.msg.GroupChatRequestMessage;
import me.chan.chatting.server.msg.GroupChatResponseMessage;

import java.util.List;

@Slf4j
@ChannelHandler.Sharable
public class GroupChatInboundHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {

        String groupName = msg.getGroupName();
        String content = msg.getContent();
        String fromUser = msg.getFrom();

        List<Channel> channels = GroupServiceFactory.getInstance().getMembersChannel(groupName);
        channels.stream().forEach(ch -> ch.writeAndFlush(new GroupChatResponseMessage(fromUser, content)));
    }
}
